package com.powerunion.datacollection.web.struts;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.powerunion.datacollection.common.BsResponse;
import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.ExcelImportHandler;
import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.config.ConfigUtil;
import com.powerunion.datacollection.model.ApproveWorkItem;
import com.powerunion.datacollection.model.MaintblData;
import com.powerunion.datacollection.service.ApproveWorkItemManager;
import com.powerunion.datacollection.service.FormGroupHeaderManager;
import com.powerunion.datacollection.service.MaintblDataManager;
import com.powerunion.datacollection.service.SubFormDataManager;
import com.powerunion.datacollection.service.SubmissionWorkItemManager;
import com.powerunion.datacollection.transaction.Transaction;
import com.powerunion.datacollection.transaction.TransactionHelper;
import com.powerunion.util.log.LogHelper;

public class SubFormDataAction extends BaseAction {

	private static final Logger logger = LogHelper.getInstance().getLogger(
			SubFormDataAction.class);
	private SubFormDataManager manager = null;

	public SubFormDataAction() {
		super();
		this.manager = new SubFormDataManager();
	}

	public void finalize() throws Throwable {
		this.manager = null;
		super.finalize();
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String subFormData = request.getParameter("subFormData");
		String formId = request.getParameter("formId");
		String submiUser = request.getRemoteUser();
		String procId = request.getParameter("procId");
		String workItemId = request.getParameter("workItemId");
		String mainTblFormValuesStr = request
				.getParameter("mainTblFormValuesStr");
		int rowFixed =  request.getParameter("rowFixed") == null ? 0
				: Integer.parseInt(request.getParameter("rowFixed"));
		int requestType = request.getParameter("requestType") == null ? 1
					: Integer.parseInt(request.getParameter("requestType"));

		boolean flag = false;
		String adminName = ConfigUtil.getInstance().getParameter(
				"system.manager.name");

		if (StringUtils.isEmpty(adminName)) {
			throw new Exception("请配置系统管理员！");
		}
		if (!adminName.equals(submiUser)) {// 如果不是管理员身份则需要检查报送任务状态
			SubmissionWorkItemManager swi = new SubmissionWorkItemManager();
			flag = swi.iSubWorkCommit(workItemId);
			if (flag) {
				this.renderFAILUREJson(response, "该任务已经结束！不能提交！");
				return null;
			}
		}

		boolean mainFlag = false;
		MaintblData data = new MaintblData();
		data.setFormId(formId);
		data.setActId(workItemId);
		data.setProcId(procId);
		data.setSubmiUser(submiUser);

		Transaction maintblDatatransaction = null;
		try {
			maintblDatatransaction = TransactionHelper.getTransaction();
			maintblDatatransaction.begin();
			logger.debug("主表报送信息:" + mainTblFormValuesStr);

			// 保存主表报送区数据
			if (!StringUtils.isEmpty(mainTblFormValuesStr)) {
				mainFlag = manager.save4MainTbl(data, mainTblFormValuesStr);
			} else {
				mainFlag = true;
			}
			maintblDatatransaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				maintblDatatransaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				maintblDatatransaction = null;
				this.renderFAILUREJson(response);
			}
		}

		if (mainFlag) {
			if (!StringUtils.isEmpty(subFormData)) {
				Transaction transaction = null;
				try {
					transaction = TransactionHelper.getTransaction();
					transaction.begin();
					logger.debug("从表报送信息:" + subFormData);

					flag = this.manager.save4SubTbl(data, subFormData);
					if(requestType != Constants.FORM_DATA_TYPE_DESIGN){
						SubmissionWorkItemManager swm = new SubmissionWorkItemManager();
						int state = swm.getState(data.getActId());
						if (state == Constants.SUBMISSION_WAIT) {
							flag = swm.updateState4User(
									Constants.SUBMISSION_NOTSUBMIT, workItemId);
						}
					}
					transaction.commit();
				} catch (Exception e) {
					logger.error("", e);
					try {
						transaction.rollback();
					} catch (Exception e1) {
						logger.error("", e1);
						throw e;
					} finally {
						transaction = null;
						this.renderFAILUREJson(response);
					}
				}
			} 
		} else {
			this.renderFAILUREJson(response,"保存主表信息失败！");
		}
		
		if (flag) {
			if(requestType == Constants.FORM_DATA_TYPE_DESIGN){
				Transaction transaction = null;
				try {
					transaction = TransactionHelper.getTransaction();
					transaction.begin();
					FormGroupHeaderManager fhm = new FormGroupHeaderManager();
					flag = fhm.update4RowFixed(formId, rowFixed);
					transaction.commit();
				} catch (Exception e) {
					logger.error("", e);
					try {
						transaction.rollback();
					} catch (Exception e1) {
						logger.error("", e1);
						throw e;
					} finally {
						transaction = null;
						this.renderFAILUREJson(response);
					}
				}
			}
		}else{
			this.renderFAILUREJson(response,"保存从表信息失败！");
		}
		
		if(flag){
			this.renderSuccssJson(response);
		}else{
			this.renderFAILUREJson(response);
		}

		return null;
	}

	public ActionForward getMaintblDataInfo(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String formId = request.getParameter("formId");
		String submiUser = request.getRemoteUser();
		String procId = request.getParameter("procId");
		String workItemId = request.getParameter("workItemId");
		int requestType = request.getParameter("requestType") == null ? 1
				: Integer.parseInt(request.getParameter("requestType"));

		MaintblData data = new MaintblData();
		data.setFormId(formId);
		data.setSubmiUser(submiUser);
		data.setProcId(procId);
		data.setActId(workItemId);

		String result = "";
		result = this.manager.getMaintblDataInfo4SubFormMaintTbl(data,
				requestType);
		logger.debug("getMaintblDataInfo:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}

	public ActionForward getSubFormData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String formId = request.getParameter("formId");
		String submiUser = request.getRemoteUser();
		String procId = request.getParameter("procId");
		String workItemId = request.getParameter("workItemId");
		int requestType = request.getParameter("requestType") == null ? 1
				: Integer.parseInt(request.getParameter("requestType"));

		MaintblData data = new MaintblData();
		data.setFormId(formId);
		data.setSubmiUser(submiUser);
		data.setProcId(procId);
		data.setActId(workItemId);

		String adminName = ConfigUtil.getInstance().getParameter(
				"system.manager.name");
		boolean flag = false;
		String result = "";

		if (StringUtils.isEmpty(adminName)) {
			throw new SystemException("请配置系统管理员！");
		}
		if(requestType != Constants.FORM_DATA_TYPE_READ){
			if (!adminName.equals(submiUser)) {// 如果不是管理员身份则需要检查报送任务状态
				SubmissionWorkItemManager swi = new SubmissionWorkItemManager();
				flag = swi.iSubWorkCommit(workItemId);
				if (flag) {
					this.renderFAILUREJson(response, "该任务已经结束！不能提交！");
					return null;
				}
			}
		}
		
		result = this.manager.getSubFormData(data, requestType);

		logger.debug("getSubFormData:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}

	public ActionForward submission(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String subFormData = request.getParameter("subFormData");
		String formId = request.getParameter("formId");
		String submiUser = request.getRemoteUser();
		String procId = request.getParameter("procId");
		String workItemId = request.getParameter("workItemId");
		String mainTblFormValuesStr = request
				.getParameter("mainTblFormValuesStr");
		String actId = request.getParameter("actId");
		String nextActivityId = request.getParameter("nextActivityId");

		SubmissionWorkItemManager swManager = new SubmissionWorkItemManager();

		boolean flag = false;
		String adminName = ConfigUtil.getInstance().getParameter(
				"system.manager.name");

		if (StringUtils.isEmpty(adminName)) {
			throw new Exception("请配置系统管理员！");
		}
		if (!adminName.equals(submiUser)) {// 如果不是管理员身份则需要检查报送任务状态
			flag = swManager.iSubWorkCommit(workItemId);
			if (flag) {
				this.renderFAILUREJson(response, "该任务已经结束！不能提交！");
				return null;
			}
		}
		
		boolean mainFlag = false;
		MaintblData data = new MaintblData();
		data.setFormId(formId);
		data.setActId(workItemId);
		data.setProcId(procId);
		data.setSubmiUser(submiUser);

		Transaction maintblDatatransaction = null;
		try {
			maintblDatatransaction = TransactionHelper.getTransaction();
			maintblDatatransaction.begin();
			logger.debug("主表报送信息:" + mainTblFormValuesStr);

			// 保存主表报送区数据
			if (!StringUtils.isEmpty(mainTblFormValuesStr)) {
				mainFlag = manager.save4MainTbl(data, mainTblFormValuesStr);
			} else {
				mainFlag = true;
			}
			maintblDatatransaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				maintblDatatransaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				maintblDatatransaction = null;
				this.renderFAILUREJson(response);
			}
		}
		boolean subFormFlag = false;
		if (mainFlag) {
			if (!StringUtils.isEmpty(subFormData)) {
				Transaction subFormTransaction = null;
				try {
					subFormTransaction = TransactionHelper.getTransaction();
					subFormTransaction.begin();
					logger.debug("从表报送信息:" + subFormData);

					subFormFlag = this.manager.save4SubTbl(data, subFormData);

					subFormTransaction.commit();
				} catch (Exception e) {
					logger.error("", e);
					try {
						subFormTransaction.rollback();
					} catch (Exception e1) {
						logger.error("", e1);
						throw e;
					} finally {
						subFormTransaction = null;
						subFormFlag = false;
					}
				}
			}
		}else{
			this.renderFAILUREJson(response,"保存主表信息失败！");
			return null;
		}
		
		if(subFormFlag){
			BsResponse br = new BsResponse();
			Transaction transaction = null;
			response.setContentType("text/json;charset=utf-8");
			try {
				transaction = TransactionHelper.getTransaction();
				transaction.begin();
				br = swManager.submission4SubTbl(actId, workItemId, formId,
						nextActivityId);

				if (br.getReturnFlag() == BsResponse.SUCCEED_FLAG) {
					this.renderSuccssJson(response);
				} else {
					this.renderFAILUREJson(response, br.getReturnMsg());
				}

				transaction.commit();
			} catch (Exception e) {
				logger.error("", e);
				try {
					transaction.rollback();
				} catch (Exception e1) {
					logger.error("", e1);
					throw e;
				} finally {
					transaction = null;
					this.renderFAILUREJson(response);
				}
			}
		}else{
			this.renderFAILUREJson(response, "保存从表信息失败！");
		}

		
		return null;
	}

//	private boolean permitSubmit(String submiUser, String workItemId,
//			HttpServletResponse response) {
//		boolean flag = false;
//		String adminName = ConfigUtil.getInstance().getParameter(
//				"system.manager.name");
//
//		if (StringUtils.isEmpty(adminName)) {
//			throw new Exception("请配置系统管理员！");
//		}
//		if (!adminName.equals(submiUser)) {// 如果不是管理员身份则需要检查报送任务状态
//			SubmissionWorkItemManager swi = new SubmissionWorkItemManager();
//			flag = swi.iSubWorkCommit(workItemId);
//			if (flag) {
//				this.renderFAILUREJson(response, "该任务已经结束！不能提交！");
//				return null;
//			}
//		}
//		return flag;
//	}
	
	public ActionForward getMaintblData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String actId = request.getParameter("actId");
		String procId = request.getParameter("procId");
		int currentOrparent = Integer.parseInt(request
				.getParameter("collectDataType"));

//		MaintblDataManager mdm = new MaintblDataManager();
//		String result = mdm.getAllMaintblDatasByAct(procId, actId,
//				currentOrparent);
		String result = this.manager.getAllMaintblDatasByAct(procId, actId,
				currentOrparent);
		logger.debug("getMaintblData:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			response.getWriter().write("{failure:true}");
		}
		return null;
	}
	
	public ActionForward getSubFormData4Approve(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String procId = request.getParameter("procId");
		String approveId = request.getParameter("workItemId");
		String actId = request.getParameter("actId");
		int requestType = request.getParameter("requestType") == null ? 1
				: Integer.parseInt(request.getParameter("requestType"));

		String currentUser = request.getRemoteUser();

		String adminName = ConfigUtil.getInstance().getParameter(
				"system.manager.name");
		boolean flag = false;
		String result = "";

		if (StringUtils.isEmpty(adminName)) {
			throw new SystemException("请配置系统管理员！");
		}
		if(requestType != Constants.FORM_DATA_TYPE_READ){
			if (!adminName.equals(currentUser)) {// 如果不是管理员身份则需要检查报送任务状态
				ApproveWorkItemManager awm = new ApproveWorkItemManager();
				flag = awm.iApproveWorkCommit(approveId);
				if (flag) {
					this.renderFAILUREJson(response, "该任务已经结束！不能操作！");
					return null;
				}
			}
		}
		
		
		ApproveWorkItemManager awm = new ApproveWorkItemManager();
		ApproveWorkItem awi = awm.getByKey(approveId);
		SubmissionWorkItemManager swm = new SubmissionWorkItemManager();
		List submissionWorkItems = new ArrayList();
		if (requestType == Constants.DATACOLLECTVIEW_REQUEST_TYPE_SUBMIDATA) {// 请求的是当前上报的任务数据
			// 得到当前上报的步骤类型
			int preActType = awi.getPreActType();
			String preActId = awi.getPreActId();

			// 当前上报的是采集步骤
			if (preActType == Constants.COLLECTION_STEP_TYPE) {
				submissionWorkItems = swm.getAllSubWorksByAct(procId, preActId,
						1);
			} else if (requestType == Constants.APPROVE_STEP_TYPE) {
				submissionWorkItems = swm.getAllSubWorksByAct(procId, preActId,
						2);
			}

		} else if (requestType == Constants.DATACOLLECTVIEW_REQUEST_TYPE_COLLECT) {// 请求的是汇总所有上报数据
			submissionWorkItems = swm.getAllSubWorksByAct(procId, actId, 2);
		}
		
		
		result = this.manager.getSubFormData4Approve(procId, submissionWorkItems, requestType);

		logger.debug("getSubFormData4Approve:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
	public ActionForward importExcelData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ExcelImportHandler eih = new ExcelImportHandler();
		
		String actId = request.getParameter("actId");
		String procId = request.getParameter("procId");
		int currentOrparent = Integer.parseInt(request
				.getParameter("collectDataType"));

		MaintblDataManager mdm = new MaintblDataManager();
		String result = mdm.getAllMaintblDatasByAct(procId, actId,
				currentOrparent);
		
		logger.debug("getMaintblData:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			response.getWriter().write("{failure:true}");
		}
		return null;
	}
	
	

}
